//
//  ContactDetailViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-10.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GuaziAppDelegate.h"
#import "ContactDetailViewController.h"
#import "PostViewController.h"
#import "MessagePicker.h"
#import "ContactGroupViewController.h"
#import "ABContactsHelper.h"

@interface ContactDetailViewController(private)
- (void) buildToolbar;
- (void) loadProfileView;
- (void) updateUserWithABContact:(ABContact*)contact;
@end


@implementation ContactDetailViewController

@synthesize user;
@synthesize profileView;
@synthesize toolbar;
@synthesize profileViewController;


/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


- (id) initWithUser:(User*)aUser
{
    self = [super init];
	if ( self ) {
		self.user = aUser;
	}
	return self;
}
						 


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self buildToolbar];
	
	self.navigationItem.title = user.remarkName;
	
	[self loadProfileView];
}


- (void) loadProfileView
{
	if ( self.profileViewController != nil ) {
		[self.profileViewController.view removeFromSuperview];
		self.profileViewController = nil;
	}
	
	FriendDetailViewController* controller = [[FriendDetailViewController alloc] initWithUser:user];
	self.profileViewController = controller;
	
	[controller viewWillAppear:NO];
	CGRect rect = CGRectMake(0, 0, controller.view.bounds.size.width, controller.view.bounds.size.height);
	controller.view.frame = rect;
	profileView.contentSize = controller.view.bounds.size;
	[profileView addSubview:controller.view];
	[controller viewDidAppear:NO];
	[controller release];
}


- (void) buildToolbar
{
	NSMutableArray* toolbarItems = [NSMutableArray array];
	
	UIBarButtonItem* editItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
																			   target:self action:@selector(setUserGroup)] autorelease];
	[toolbarItems addObject:editItem];
	
	if ( [user.relation compare:kUserRelationBoth]==NSOrderedSame ) {
		UIBarButtonItem* dmItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
																				 target:self action:@selector(postDirectMessage)] autorelease];
		[toolbarItems addObject:dmItem];
	}
	
	if ( user.userId > 0 ) {
		UIBarButtonItem* tweetItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
																					target:self action:@selector(postTweet)] autorelease];
		[toolbarItems addObject:tweetItem];
	}
	
	if ( user.contact ) {
		UIBarButtonItem* phoneItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay 
																					target:self action:@selector(callPhone)] autorelease];
		[toolbarItems addObject:phoneItem];
		
		UIBarButtonItem* messageItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply
																					  target:self action:@selector(sendMessage)] autorelease];
		[toolbarItems addObject:messageItem];
	}
	else {
		UIBarButtonItem* addToContactButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks 
																							 target:self action:@selector(addToContact)] autorelease];
		[toolbarItems addObject:addToContactButton];
	}
	
	if ( user.userId > 0 ) {
		UIBarButtonItem* refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
																						target:self action:@selector(refresh)] autorelease];
		[toolbarItems addObject:refreshButton];
		
		if ( user.following ) {
			UIBarButtonItem* cancelFollowingButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash 
																									target:self action:@selector(destroyFriendShip)] autorelease];
			[toolbarItems addObject:cancelFollowingButton];
		}
		else {
			UIBarButtonItem* createFollowingButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																									target:self action:@selector(createFriendship)] autorelease];
			[toolbarItems addObject:createFollowingButton];
		}
	}
	
	NSMutableArray* arr = [NSMutableArray arrayWithCapacity:2*[toolbarItems count]-1];
	UIBarButtonItem* item = nil;
	UIBarButtonItem* space = nil;
	
	for ( int i=0; i<[toolbarItems count]; i++ ) {
		item = [toolbarItems objectAtIndex:i];
		[arr addObject:item];
		if ( i != [toolbarItems count] - 1 ) {
			space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
																   target:self action:nil] autorelease];
			[arr addObject:space];
		}
	}
	
	toolbar.items = arr;
}


//设置分组
- (void) setUserGroup
{
	ContactGroupViewController* controller = [[ContactGroupViewController alloc] initWithStyle:UITableViewStylePlain user:self.user];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//发私信
- (void)postDirectMessage
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView editDirectMessage:user.screenName];
}


//发动态
- (void) postTweet
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView reply:user.screenName];
}


//发短信
- (void) sendMessage
{
	NSArray* array = [NSArray arrayWithObject:user.phone];
	MessagePicker* picker = [[MessagePicker alloc] initWithController:self recienpts:array body:@""];
	[picker send];
	[picker release];
}

//打电话
- (void) callPhone
{
	NSString* url = [NSString stringWithFormat:@"tel://%@", user.phone];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

//刷新
- (void) refresh
{
	[self loadProfileView];
}

//取消关注
- (void) destroyFriendShip
{
	UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"确认要取消关注？" 
															 delegate:self 
													cancelButtonTitle:@"取消" 
											   destructiveButtonTitle:@"确定" 
													otherButtonTitles:nil];
	[actionSheet showInView:self.view];
	[actionSheet release];
}


- (void) actionSheet:(UIActionSheet*)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if ( [actionSheet.title compare:@"确认要取消关注？"]==NSOrderedSame ) {
		//取消关注
		if ( buttonIndex == [actionSheet cancelButtonIndex] ) return;
		
		if ( client ) {
			return;
		}
		
		client = [[TwitterClient alloc] initWithTarget:self action:@selector(didDestroyFriendship:obj:)];
		[client friendship:user.userId create:NO];
	}
	else {
		//添加到通讯录
		if ( buttonIndex == 0 ) {
			//绑定现有联系人
			ABPeoplePickerNavigationController *ppnc = [[ABPeoplePickerNavigationController alloc] init];
			ppnc.peoplePickerDelegate = self;
			[self presentModalViewController:ppnc animated:YES];
            [ppnc release];
			
		}
		else if ( buttonIndex == 1 ) {
			//增加联系人
			// create a new view controller
			ABContact *contact = [ABContact contact];
			contact.firstname = user.screenName;
			
			//email
			NSRange range = [user.name rangeOfString:@"@"];
			if ( range.location != NSNotFound ) {
				NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:user.name, @"_$!<Home>!$_", nil];
				contact.emailDictionaries = [NSArray arrayWithObject:dic];
			}
			
			//phone
			if ( user.phone != nil && [user.phone length]>0 ) {
				NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:user.phone, @"_$!<Mobile>!$_", nil];
				contact.phoneDictionaries = [NSArray arrayWithObject:dic];
			}
			
			//address
			/*
			NSDictionary* dic = [ABContact addressWithStreet:@"" 
												   withCity:user.cityName withState:user.provinceName 
													withZip:@"" withCountry:@"China" withCode:@"cn"];
			contact.addressDictionaries = [NSArray arrayWithObject:dic];
			*/
			 
			//photo
			if ( user.profileImageUrl_s && [user.profileImageUrl_s length]>0 ) {
				UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:user.profileImageUrl_s]]];
				contact.image = image;
			}
			else {
				UIImage* image = [ImageStore defaultProfileImage:NO];
				contact.image = image;
			}
			
			ABNewPersonViewController *npvc = [[ABNewPersonViewController alloc] init];
			npvc.newPersonViewDelegate = self;
			npvc.displayedPerson = contact.record;
			npvc.title = @"新联系人";
			//[self presentModalViewController:npvc animated:YES];
			[self.navigationController pushViewController:npvc animated:YES];
            [npvc release];
		}
	}

}


- (void) didDestroyFriendship:(id)sender obj:(NSObject*)obj
{
	client = nil;
	
	TwitterClient* tc = (TwitterClient*)sender;
	if ( tc.hasError ) {
		[tc alert];
	}
	else {
		user.following = NO;
		if ( [user.relation compare:kUserRelationBoth] == NSOrderedSame ) {
			user.relation = kUserRelationFollower;
		}
		else if ( [user.relation compare:kUserRelationFollowing] == NSOrderedSame ) {
			user.relation = kUserRelationNone;
		}
		[user updateDB:YES withName:NO withAccount:NO];
		
		//toolbar.items = nil;
		[self buildToolbar];
		[self loadProfileView];
	}
}


//关注
- (void) createFriendship
{
	if ( client ) {
		return;
	}
	
	client = [[TwitterClient alloc] initWithTarget:self action:@selector(didCreateFriendship:obj:)];
	[client friendship:user.userId create:YES];
}


- (void) didCreateFriendship:(id)sender obj:(NSObject*)obj
{
	client = nil;
	
	TwitterClient* tc = (TwitterClient*)sender;
	if ( tc.hasError ) {
		[tc alert];
	}
	else {
		user.following = YES;
		if ( [user.relation compare:kUserRelationFollower] == NSOrderedSame ) {
			user.relation = kUserRelationBoth;
		}
		else if ( [user.relation compare:kUserRelationNone] == NSOrderedSame ) {
			user.relation = kUserRelationFollowing;
		}
		[user updateDB:YES withName:NO withAccount:NO];
		
		//toolbar.items = nil;
		[self buildToolbar];
		[self loadProfileView];
	}
}


//增加联系人
- (void) addToContact
{
	UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"将好友添加到本机通讯录" 
															 delegate:self
													cancelButtonTitle:@"取消"
											   destructiveButtonTitle:@"绑定到现有联系人" 
													otherButtonTitles:@"创建新联系人",nil];
	[actionSheet showInView:self.view];
	[actionSheet release];
}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
	ABContact* abContact = [ABContact contactWithRecord:person];
	[self updateUserWithABContact:abContact];
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
	// required method that is never called in the people-only-picking
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
	return NO;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
}


#pragma mark NEW PERSON DELEGATE METHODS
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person
{
	if (person)
	{
		ABContact *contact = [ABContact contactWithRecord:person];
		if (![ABContactsHelper addContact:contact withError:nil])
		{
			// may already exist so remove and add again to replace existing with new
			[contact removeSelfFromAddressBook:nil];
			[ABContactsHelper addContact:contact withError:nil];
		}
		
		[self updateUserWithABContact:contact];
	}
	
	[self.navigationController popViewControllerAnimated:YES];
}


- (void) updateUserWithABContact:(ABContact*)abContact
{
	user.contact = YES;
	user.contactName = [abContact compositeName];
	NSArray* arr = abContact.phoneArray;
	if ( arr != nil && [arr count] > 0 ) {
		user.phone = [abContact.phoneArray objectAtIndex:0];
	}
	[user updateDB:YES withName:YES withAccount:NO];
	[self buildToolbar];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.profileView = nil;
	self.toolbar = nil;
	self.user = nil;
	self.profileViewController = nil;
	
	if ( client ) {
		[client cancel];
	}
	[client release];
}


- (void)dealloc {
	[user release];
	[profileView release];
	[toolbar release];
	[profileViewController release];
	if ( client ) [client cancel];
	[client release];
    [super dealloc];
}


@end
